package com.byl.modules.core.service.impl;

import ch.qos.logback.core.joran.spi.NoAutoStart;
import com.byl.common.modules.service.BaseServiceImpl;
import com.byl.modules.core.dao.CustomerDao;
import com.byl.modules.core.dao.LoanDao;
import com.byl.modules.core.service.LoanService;
import com.byl.sdk.utils.DateUtils;
import com.byl.sdk.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.spring5.processor.SpringActionTagProcessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoanServiceImpl extends BaseServiceImpl<LoanDao> implements LoanService {

    //用来存放当前各个总代的最大编号   用代理的编码作为key 存储当前代理的最大编号
    private Map<String, String> LOAN_CURRENT_NUM = new HashMap<>();
    @Autowired
    CustomerDao customerDao;

    @Override
    public int applySuccess(Map map) {
        //1.更新客户状态  将其表示为已完成
        customerDao.updateCustomerStatus(MapUtils.getValue(map,"cid"),"4");
        //更新贷款单状态
        baseDao.update(map);
        //1.查询相关利益合伙人
        Map userMap=baseDao.queryCommissionInfo(MapUtils.getValue(map,"id"));
        return saveCommission(userMap,MapUtils.getValue(map,"id"));
    }

    /**
     * 保存佣金明细
     * @return
     */
    private int saveCommission(Map map,String lid){
      if(null==map)
          return 0;
      //定义集合对象
        List<Map> list=new ArrayList<>();
        double applyAmount=MapUtils.getDoubleValue(map,"applyAmount");//贷款金额

        list.add(getCommissionMap(map, lid, applyAmount, "oneCommission", "coding", "userId"));//一级佣金
        list.add(getCommissionMap(map, lid, applyAmount, "twoCommission", "twoCoding", "twoUserId")); //二级佣金
        list.add(getCommissionMap(map, lid, applyAmount, "thirdCommission", "thirdCoding", "thirdUserId")); //三级佣金

        return baseDao.saveBatchCommission(list);

    }

    /**
     * 获取相关合伙人的佣金信息
     * @param map   相关利益合伙人信息
     * @param lid  申请人id
     * @param applyAmount  贷款金额
     * @param _commission  佣金比例
     * @param _userid  合伙人
     * @param _coding   合伙人编码
     * @return
     */

    private Map getCommissionMap(Map map,String lid,double applyAmount,String _commission,String _userid,String _coding){

        double commission=MapUtils.getDoubleValue(map,_commission);
        String userId=MapUtils.getValue(map,_userid);
        String coding=MapUtils.getValue(map,_coding);
        //计算佣金
        double total=applyAmount*commission;
        Map tmpMap=new HashMap();
        tmpMap.put("lid",lid);
        tmpMap.put("userId",userId);
        tmpMap.put("coding",coding);
        tmpMap.put("money",applyAmount);
        tmpMap.put("commission_rate",commission);
        tmpMap.put("commission",total);
        tmpMap.put("note","");
        return  tmpMap;
    }

    @Transactional
    @Override
    public int save(Map map) {
        //更新客户状态
        customerDao.updateCustomerStatus(MapUtils.getValue(map, "cid"), "3");
        //申请编号
        map.put("loanNum",generateLoanNum(MapUtils.getValue(map,"userCoding")));
        return baseDao.save(map);
    }

    /**
     * 生成贷款编号
     *
     * @param coding 操作员的编号
     * @return
     */
    String generateLoanNum(String coding) {
        //当前最大编号
        String currentNum = "";
        //获取当前系统年月
        String rq = DateUtils.formatDateForYmDate();
        //获取当前操作员所在代理编码
        String proxy = coding.substring(0, 2);
        //判断内存中是否有当前代理的编号
        if (LOAN_CURRENT_NUM.containsKey(proxy)) {
            //从内存中获取当前代理的最大贷款编号
            currentNum = LOAN_CURRENT_NUM.get(proxy);
        } else {
            //说明内存中没有 从数据库查询当前代理的最大编号
            currentNum = baseDao.queryMaxNum(proxy);
            //判断数据库中是否存在
            if (null == currentNum) {
                String tmp="dk"+proxy+rq+"0001";
                //将编号保存到内存中
                LOAN_CURRENT_NUM.put(proxy,tmp);
                //不存在 产生一个默认的编号
                return tmp;
            }
        }
        //到此已经确定最大编号 currentNum
        return null;
    }

    /**
     * @param currentNum 当前已存在的最大编号  dk102022010001
     * @param ym
     * @return
     */
    private String getNextNum(String currentNum, String ym) {
        String nextNum="";
        //获取最大编号的年月
        String tmp = currentNum.substring(4, 10);
        //对比当前系统年月
        if (tmp.equals(ym)) {
            //说明是同一个月内的下一笔贷款单
            //截取编码后4位
            String num = currentNum.substring(10);
            //转换为数字
            int n = Integer.parseInt(num);
            n++;

            nextNum= currentNum.substring(0, 10) + String.format("%04d", n);
        } else {
            nextNum= "dk" + currentNum.substring(0, 2) + ym + "0001";
        }
        //保存到内存中
        LOAN_CURRENT_NUM.put(nextNum.substring(2,4),nextNum);
        return nextNum;

    }
}


